package com.fanyue.modules.wzb.service.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.fanyue.core.base.BaseServiceImpl;
import com.fanyue.core.cache.CoolCache;
import com.fanyue.core.util.CoolSecurityUtil;
import com.fanyue.core.util.DatabaseDialectUtils;
import com.fanyue.modules.wzb.entity.ClothingRecordEntity;
import com.fanyue.modules.wzb.mapper.ClothingRecordMapper;
import com.fanyue.modules.wzb.service.ClothingRecordService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.tangzc.autotable.core.constants.DatabaseDialect;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.fanyue.modules.base.entity.sys.table.BaseSysDepartmentEntityTableDef.BASE_SYS_DEPARTMENT_ENTITY;
import static com.fanyue.modules.base.entity.sys.table.BaseSysUserEntityTableDef.BASE_SYS_USER_ENTITY;
import static com.fanyue.modules.wzb.entity.table.AppUserEntityTableDef.APP_USER_ENTITY;
import static com.fanyue.modules.wzb.entity.table.AppUserFaceRecordEntityTableDef.APP_USER_FACE_RECORD_ENTITY;
import static com.fanyue.modules.wzb.entity.table.CargoEntityTableDef.CARGO_ENTITY;
import static com.fanyue.modules.wzb.entity.table.ClothingInfoEntityTableDef.CLOTHING_INFO_ENTITY;
import static com.fanyue.modules.wzb.entity.table.ClothingRecordEntityTableDef.CLOTHING_RECORD_ENTITY;
import static com.fanyue.modules.wzb.entity.table.ClothingSpecEntityTableDef.CLOTHING_SPEC_ENTITY;


/**
 * 系统用户
 */
@Service
@RequiredArgsConstructor
public class ClothingRecordServiceImpl extends BaseServiceImpl<ClothingRecordMapper, ClothingRecordEntity> implements ClothingRecordService {

    final private CoolCache coolCache;

    @Override
    public Object page(JSONObject requestParams, Page<ClothingRecordEntity> page, QueryWrapper qw) {
        String modularType = requestParams.getStr("modularType");
        String dateStartTime = requestParams.getStr("dateStartTime");
        String dateEndTime = requestParams.getStr("dateEndTime");
        String clothingCode = requestParams.getStr("clothingCode");
        String cargoPosition = requestParams.getStr("cargoPosition");
        String appUserName = requestParams.getStr("appUserName");
        String orgAndPeople = requestParams.getStr("orgAndPeople");
        String operator = requestParams.getStr("operator");
        String sysUserName = requestParams.getStr("sysUserName");
        Integer status = requestParams.getInt("status");
        Integer type = requestParams.getInt("type");
        Long[] departmentIds = requestParams.get("departmentIds", Long[].class);
        JSONObject tokenInfo = CoolSecurityUtil.getAdminUserInfo(requestParams);
        // 用户的部门权限
        Long[] permsDepartmentArr = coolCache.get("admin:department:" + tokenInfo.get("userId"),
                Long[].class);
        String databaseDialect = DatabaseDialectUtils.getDatabaseDialect();
        if (databaseDialect.equals(DatabaseDialect.PostgreSQL)) {
            // 兼容postgresql
            qw.select("base_sys_department.name AS departmentName");
        } else {
            qw.select(CLOTHING_RECORD_ENTITY.ALL_COLUMNS,
                    APP_USER_ENTITY.NAME.as("appUserName"),
                    BASE_SYS_DEPARTMENT_ENTITY.NAME.as("departmentName"));
        }
        qw.from(CLOTHING_RECORD_ENTITY)
                .leftJoin(APP_USER_ENTITY)
                .on(CLOTHING_RECORD_ENTITY.APP_USER_ID.eq(APP_USER_ENTITY.ID))
                .leftJoin(BASE_SYS_DEPARTMENT_ENTITY)
                .on(CLOTHING_RECORD_ENTITY.DEPARTMENT_ID.eq(BASE_SYS_DEPARTMENT_ENTITY.ID));

        List<Integer> typeList = new ArrayList<>();

        //操作类型，1-借出，2-归还，3-调货（减少），4-转库（增加）,5-上架，6-下架, 7-外部借出, 8-外部归还
        if (modularType.equals("appUser")) {
            typeList.add(1);
            typeList.add(2);
        }
        if (modularType.equals("upDown")) {
            typeList.add(5);
            typeList.add(6);
        }
        if (modularType.equals("batch")) {
            typeList.add(7);
            typeList.add(8);
        }

        qw.and(CLOTHING_RECORD_ENTITY.TYPE.in(typeList, typeList.size() > 0));
        // 筛选状态
        qw.and(CLOTHING_RECORD_ENTITY.STATUS.eq(status, status != null));
        qw.and(CLOTHING_RECORD_ENTITY.TYPE.eq(type, type != null));

        if (StrUtil.isNotEmpty(dateStartTime)) {
            qw.and(CLOTHING_RECORD_ENTITY.CREATE_TIME.ge(dateStartTime));
        }
        if (StrUtil.isNotEmpty(dateEndTime)) {
            qw.and(CLOTHING_RECORD_ENTITY.CREATE_TIME.le(dateEndTime));
        }
        if (StrUtil.isNotEmpty(clothingCode)) {
            qw.and(CLOTHING_RECORD_ENTITY.CLOTHING_CODE.like(clothingCode));
        }
        if (StrUtil.isNotEmpty(cargoPosition)) {
            qw.and(CLOTHING_RECORD_ENTITY.CARGO_POSITION.like(cargoPosition));
        }
        if (StrUtil.isNotEmpty(orgAndPeople)) {
            qw.and(CLOTHING_RECORD_ENTITY.ORG_AND_PEOPLE.like(orgAndPeople));
        }
        if (StrUtil.isNotEmpty(operator)) {
            qw.and(CLOTHING_RECORD_ENTITY.OPERATOR.like(operator));
        }
        if (StrUtil.isNotEmpty(appUserName)) {
            qw.and(APP_USER_ENTITY.NAME.like(appUserName));
        }
        if (StrUtil.isNotEmpty(sysUserName)) {
            qw.and(CLOTHING_RECORD_ENTITY.SYS_USER_NAME.like(sysUserName));
        }

        // 筛选部门
        qw.and(CLOTHING_RECORD_ENTITY.DEPARTMENT_ID.in(departmentIds,
                ArrayUtil.isNotEmpty(departmentIds)));
        // 过滤部门权限
        qw.and(CLOTHING_RECORD_ENTITY.DEPARTMENT_ID.in(
                permsDepartmentArr == null || permsDepartmentArr.length == 0 ? new Long[]{null}
                        : permsDepartmentArr,
                !CoolSecurityUtil.getAdminUsername().equals("admin")));
        if (databaseDialect.equals(DatabaseDialect.PostgreSQL)) {
            // 兼容postgresql
            qw.groupBy("base_sys_department.name");
        } else {
            qw.groupBy(CLOTHING_RECORD_ENTITY.ID);
        }
        return mapper.paginate(page, qw);
    }

    @Override
    public List<ClothingRecordEntity> listByInfo(ClothingRecordEntity info) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select(CLOTHING_RECORD_ENTITY.ALL_COLUMNS);
        queryWrapper.from(CLOTHING_RECORD_ENTITY);
        queryWrapper.and(CLOTHING_RECORD_ENTITY.FACE_RECORD_ID.in(info.getFaceRecordIds(), info.getFaceRecordIds() == null));
        return mapper.selectListByQuery(queryWrapper);
    }
}